﻿/* 
* Copyright (c) 2009, The University of Texas at Austin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, 
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, 
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, 
* this list of conditions and the following disclaimer in the documentation and/or other materials 
* provided with the distribution.
*
* Neither the name of The University of Texas at Austin nor the names of its contributors may be 
* used to endorse or promote products derived from this software without specific prior written 
* permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace TaxonomyLoader
{
    class Program
    {
        /// <summary>
        /// This program simply takes an NCBI taxonomy dump and formats the
        /// Taxonomy tables...this is a starting point for bootstrapping the rCAD
        /// reference instance. The reference instance can be updated using the RNAJOIN
        /// SSIS package that will ship with it.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string NodeFormat = @"(?<TaxID>[0-9]+)\t\|\t(?<ParentTaxID>[0-9]+)\t\|\t(?<Rank>[^\t\|]+)\t\|\t(?<EMBLCode>[^\t\|]*)\t\|\t(?<DivID>[0-9]+)\t\|\t(?<InheritedDivFlag>[0|1])\t\|\t(?<GenCodeID>[0-9]+)\t\|\t(?<InheritedGCFlag>[0|1])\t\|\t(?<MitoGenCodeID>[0-9]+)\t\|\t(?<InheritedMCGCFlag>[0|1])\t\|\t(?<GBHiddenFlag>[0|1])\t\|\t(?<HiddenRootSubtreeFlag>[0|1])\t\|\t(?<Comments>[^\t\|]*)\t\|";

            Console.WriteLine("Constructing the Taxonomy Table");

            using (var taxonomyoutput = File.CreateText("Taxonomy.dat"))
            {
                using (var nodesInput = File.OpenText("nodes.dmp"))
                {
                    string line = nodesInput.ReadLine();
                    while (!string.IsNullOrEmpty(line))
                    {
                        Match m = Regex.Match(line, NodeFormat);
                        taxonomyoutput.WriteLine("{0}\t|\t{1}", Int32.Parse(m.Groups["TaxID"].Value), Int32.Parse(m.Groups["ParentTaxID"].Value));
                        line = nodesInput.ReadLine();
                    }
                }
            }

            IEnumerable<Name> names = Name.Load("names.dmp");

            Console.WriteLine("Constructing the NameClass Table");

            //Construct the NameClass lookup table
            Dictionary<string, int> nameClasses = new Dictionary<string, int>();

            var ncs = from nc in names
                      group nc by nc.NameClass into distinctnc
                      select new { NameClassTxt = distinctnc.Key };

            using (var nameclassesoutput = File.CreateText("NameClasses.dat"))
            {
                int nameClassID = 1;
                foreach (var nct in ncs)
                {
                    nameClasses.Add(nct.NameClassTxt, nameClassID);
                    nameclassesoutput.WriteLine("{0}\t|\t{1}", nameClassID, nct.NameClassTxt);
                    nameClassID++;
                }
            }

            Console.WriteLine("Constructing the TaxonomyNames Table");

            var tns = from name in names
                      where name.NameClass.Equals("scientific name")
                      select name;

            using (var taxonomynamesoutput = File.CreateText("TaxonomyNames.dat"))
            {
                foreach (var tn in tns)
                {
                    taxonomynamesoutput.WriteLine("{0}\t|\t{1}", tn.TaxID, tn.NameText);
                }
            }

            Console.WriteLine("Constructing the AlternateNames Table");

            var ans = names.Except(tns);

            using (var alternatenamesoutput = File.CreateText("AlternateNames.dat"))
            {
                foreach (var an in ans)
                {
                    alternatenamesoutput.WriteLine("{0}\t|\t{1}\t|\t{2}", an.TaxID, nameClasses[an.NameClass], an.NameText);
                }
            }

            //Note: Fork an SSIS package for loading the data into the database?
        }
    }
}
